package com.peng.my_blog.chat.exception;


import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangshipeng
 * @Description: 通用 Api Controller 全局异常处理
 * @date 2018-11-09 15:25
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * @param e 异常类型
     * @return com.baomidou.mybatisplus.extension.api.R<java.lang.Object>
     * @Description 自定义 REST 业务异常
     * @author wangshipeng
     * @date 2018年11月09日 15:26:09
     */
    @ExceptionHandler(value = ApiException.class)
    @ResponseBody
    public R<Object> handleBadApiException(ApiException e) {
        //业务逻辑异常
        IErrorCode errorCode = e.getErrorCode();
        if (null != errorCode) {
            logger.debug("Rest request error, {}", errorCode.toString());
            return R.failed(errorCode);
        }
        logger.debug("Rest request error, {}", e.getMessage());
        return R.failed(e.getMessage());
    }

    /**
     * @param e 参数异常体
     * @return com.baomidou.mybatisplus.extension.api.R<java.lang.Object>
     * @Description 参数校验异常
     * @author wangshipeng
     * @date 2018年11月09日 15:47:53
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public R handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (null != bindingResult && bindingResult.hasErrors()) {
            List<Object> jsonList = new ArrayList<>();
            bindingResult.getFieldErrors().forEach(fieldError -> {
                Map<String, Object> jsonObject = new HashMap<>(2);
                jsonObject.put("name", fieldError.getField());
                jsonObject.put("msg", fieldError.getDefaultMessage());
                jsonList.add(jsonObject);
            });
            return R.restResult(jsonList.get(0), ApiErrorCode.FAILED);
        }
        return R.restResult(null, ApiErrorCode.FAILED);
    }

    /**
     * @param e 系统内部异常
     * @return com.baomidou.mybatisplus.extension.api.R<java.lang.Object>
     * @Description 系统内部异常，打印异常栈
     * @author wangshipeng
     * @date 2018年11月09日 15:49:27
     */
    @ExceptionHandler(value = Throwable.class)
    public ModelAndView handleSystemException(Throwable e) {
        if (e instanceof NoHandlerFoundException) {
            logger.error("没找到页面:{}", e.getMessage());
        } else {
            logger.error("Error: handleSystemException StackTrace : {}", e);
        }


        return new ModelAndView("common/error");
    }
}

